<?php
class Visitor_model extends CI_Model
{
    private $_table = 'visitor';

    public  function findByUid($uid)
    {
        $this->db->select('visitor_id, visitor_name, sex, mobile_phone, type, pin, default');
        $this->db->from($this->_table);
        $this->db->where('uid', $uid);
        $this->db->order_by('default DESC, visitor_id DESC');
        return $this->db->get();
    }

    /**
     * 查找
     */
    public function findById($visitorId)
    {
        $this->db->select('visitor_id, visitor_name, sex, mobile_phone, type, pin, default');
        $this->db->from($this->_table);
        $this->db->where('visitor_id', $visitorId);
        $this->db->limit(1);
        return $this->db->get();
    }

    /**
     * 新增
     */
    public function visitorInsert($postData)
    {
        $data = array(
            'uid' 		   => $postData['uid'],
            'visitor_name' => $postData['visitor_name'],
            'sex' 		   => (int)$postData['sex'],
            'mobile_phone' => $postData['mobile_phone'],
            'type'   	   => (int)$postData['type'],
            'pin' 		   => $postData['pin'],
            'default' 	   => 0,
            'created_at'   => date('Y-m-d H:i:s'),
            'updated_at'   => '0000-00-00 00:00:00'
        );

        $this->db->insert($this->_table, $data);
        return $this->db->insert_id();
    }

    /**
     * 编辑
     */
    public function visitorUpdate($postData)
    {
        $data = array(
            'visitor_name' => $postData['visitor_name'],
            'sex' 		   => $postData['sex'],
            'mobile_phone' => $postData['mobile_phone'],
            'type'   	   => $postData['type'],
            'pin' 		   => $postData['pin']
        );
        $this->db->where('visitor_id', $postData['visitor_id']);
        return $this->db->update($this->_table, $data);
    }

    /**
     * 删除
     */
    public function visitorDelete($visitorId, $uid)
    {
        $this->db->where('visitor_id', $visitorId);
        $this->db->where('uid', $uid);
        return $this->db->delete($this->_table);
    }

    /**
     * 设置没有默认值
     */
    public function setNoDefault($uid)
    {
        $this->db->set('default', 0);
        $this->db->where('uid', $uid);
        return $this->db->update($this->_table);
    }

    /**
     *根据id设置默认值
     */
    public function setDefaultToId($id)
    {
        $this->db->set('default', 1);
        $this->db->where('visitor_id', (int)$id);
        return $this->db->update($this->_table);
    }
}